package handler

import (
	"fmt"
	"github.com/julienschmidt/httprouter"
	"net/http"
	"net/url"
	"openwechat/config"
	"openwechat/utils/wxbizjsonmsgcrypt/epchat"
	"strings"
)

func WeChatVerifyURL(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	fmt.Println(r, r.Body)
	httpStr := r.URL.RawQuery
	start := strings.Index(httpStr, "msg_signature=")
	start += len("msg_signature=")

	var msgSignature string
	next := getString(httpStr, "&timestamp=", start, &msgSignature)

	var timestamp string
	next = getString(httpStr, "&nonce=", next, &timestamp)

	var nonce string
	next = getString(httpStr, "&echostr=", next, &nonce)

	echo := httpStr[next:len(httpStr)]

	echo, _ = url.QueryUnescape(echo)
	fmt.Println(msgSignature, timestamp, nonce, echo, next)

	wxCpt := epchat.NewWXBizMsgCrypt(config.Config.Token, config.Config.EncodingAESKey, config.Config.ReceiverId)
	echoStr, cryptErr := wxCpt.VerifyURL(msgSignature, timestamp, nonce, echo)
	if nil != cryptErr {
		fmt.Println("verifyUrl fail", cryptErr)
	}
	fmt.Println("verifyUrl success echoStr", string(echoStr))
	fmt.Fprintf(w, string(echoStr))
}
